package com.danielagarza.app;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.danielagarza.app.servicios.PublicarDatos;

public class Shake extends Activity implements SensorEventListener {
	private String m_Text = "";

	private SensorManager sensorManager;
	private List<Sensor> sensors;
	private Sensor sensor;
	private long lastUpdate = -1;
	private long currentTime = -1;
	private Location localizacion;

	private float last_x, last_y, last_z;
	private float current_x, current_y, current_z, currenForce;
	private static final int FORCE_THRESHOLD = 900;
	private final int DATA_X = SensorManager.DATA_X;
	private final int DATA_Y = SensorManager.DATA_Y;
	private final int DATA_Z = SensorManager.DATA_Z;

	private LocationManager mlocManager;
	private MyLocationListener mlocListener;

	int tokenGen = 0;
	Boolean esPadreGen = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SensorManager sensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		this.sensorManager = sensorService;
		this.sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

		if (sensors.size() > 0) {
			sensor = sensors.get(0);
		}
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		if (metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
				|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM) {
			setContentView(R.layout.activity_shake);
		} else {
			setContentView(R.layout.activity_shake_tablet);
		}

		/* Use the LocationManager class to obtain GPS locations */
		mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mlocListener = new MyLocationListener();
		mlocListener.setMainActivity(this);
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
	}

	public void initShake(View view) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);

		dialog.setTitle("INSTRUCCIONES");
		dialog.setMessage("1) ¿Es usted quien esta Registrando?.\n");
		dialog.setCancelable(false);
		dialog.setPositiveButton("Si", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				esPadreGen = Boolean.TRUE;
				generarToken();
			}
		});
		dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				esPadreGen = Boolean.FALSE;
				pedirToken();
			}
		});
		dialog.show();

	}

	private void pedirToken() {

		Toast.makeText(getBaseContext(), "Agita tu Teléfono o Tablet.",
				Toast.LENGTH_LONG).show();
		start();

	}

	private void generarToken() {

		Toast.makeText(getBaseContext(), "Agita tu Teléfono o Tablet.",
				Toast.LENGTH_LONG).show();
		start();

	}

	private class PostData extends AsyncTask<Void, Void, Void> {
		Location loca;

		public PostData(Location loca) {
			this.loca = loca;
		}

		@Override
		protected Void doInBackground(Void... arg) {
			PublicarDatos p = new PublicarDatos();
			p.vincularUsuarios(tokenGen, esPadreGen, loca);
			stop();

			return null;

		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER
				|| event.values.length < 3)
			return;

		currentTime = System.currentTimeMillis();

		if ((currentTime - lastUpdate) > 100) {
			long diffTime = (currentTime - lastUpdate);
			lastUpdate = currentTime;

			current_x = event.values[DATA_X];
			current_y = event.values[DATA_Y];
			current_z = event.values[DATA_Z];

			currenForce = Math.abs(current_x + current_y + current_z - last_x
					- last_y - last_z)
					/ diffTime * 10000;

			if (currenForce > FORCE_THRESHOLD) {

				PostData p = new PostData(localizacion);
				p.execute();

			}
			last_x = current_x;
			last_y = current_y;
			last_z = current_z;

		}

	}

	public void start() {
		if (sensor != null) {
			sensorManager.registerListener(this, sensor,
					SensorManager.SENSOR_DELAY_GAME);
		}
	}

	public void stop() {
		sensorManager.unregisterListener(this);
	}

	public void setLocation(Location loc) {
		this.localizacion = loc;
		/*
		 * if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) { try {
		 * Geocoder geocoder = new Geocoder(this, Locale.getDefault());
		 * List<Address> list = geocoder.getFromLocation( loc.getLatitude(),
		 * loc.getLongitude(), 1); if (!list.isEmpty()) { Address address =
		 * list.get(0); Toast.makeText(getBaseContext(), "Mi dirección es: \n" +
		 * address.getAddressLine(0), Toast.LENGTH_LONG).show(); }
		 * 
		 * 
		 * } catch (IOException e) { e.printStackTrace(); } }
		 */

	}

	public class MyLocationListener implements LocationListener {
		Shake mainActivity;

		public Shake getMainActivity() {
			return mainActivity;
		}

		public void setMainActivity(Shake mainActivity) {
			this.mainActivity = mainActivity;
		}

		@Override
		public void onLocationChanged(Location loc) {

			this.mainActivity.setLocation(loc);
		}

		@Override
		public void onProviderDisabled(String provider) {

			Toast.makeText(getBaseContext(), "GPS Desactivado",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onProviderEnabled(String provider) {
			// Este metodo se ejecuta cuando el GPS es activado
			Toast.makeText(getBaseContext(), "GPS Activado", Toast.LENGTH_LONG)
					.show();

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

	}/* End of Class MyLocationListener */

	@Override
	protected void onDestroy() {
		mlocManager.removeUpdates(mlocListener);
		super.onDestroy();

	}

}
